package com.aat.dxfy.execOnline;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class DynamicCompileTest2 {

	public static void main(String[] args) throws IOException {
		String source = "package temp.com.aat;\n	public class  Hello{\n		public static void main (String[] args){\n			System.out.println(\"Hello World! \");\n			System.out.println(\"\");\n			System.out.println(\"中国人! \");\n		}\n	}";

		System.out.println(runSrcMain(source, "gbk"));

		StringBuilder sb = new StringBuilder();
		sb.append("//This is a test program.\n");
		// sb.append("package temp.aat.test;\n\n");
		sb.append("public class Test{\n");
		sb.append("    public static void main(String[] args) throws Exception {\n");
		sb.append("        System.out.println(\"Hello Test Java.\");\n");
		sb.append("    }\n");
		sb.append("}");
		System.out.println(runSrcMain(sb.toString(), "utf-8"));
	}

	// s
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String runSrcMain(String source, String encode) {
		String res = "";
		try {
			if (encode == null || encode.length() == 0) {
				encode = "utf-8";
			}
			// 2.将欲动态编译的代码写入文件中 1.创建临时目录 2.写入临时文件目录
			File dir = new File(System.getProperty("user.dir") + "/temp"); // 临时目录
			// 如果 \temp 不存在 就创建
			if (!dir.exists()) {
				dir.mkdir();
			}

			// 类名称和包名称
			int i1 = source.indexOf("class") + 5;
			int i2 = source.indexOf("{");
			String fullName = source.substring(i1, i2).trim();

			String packageName = "";
			if (source.contains("package")) {
				int j1 = source.indexOf("package") + 7;
				int j2 = source.indexOf(";");
				packageName = source.substring(j1, j2).trim().replaceAll("\\.", "/") + "/";
			} else {
				packageName = "";
			}

			FileWriter writer = new FileWriter(new File(dir, fullName + ".java"));
			writer.write(source);
			writer.flush();
			writer.close();

			// 3.取得当前系统的编译器
			JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
			// 4.获取一个文件管理器
			StandardJavaFileManager javaFileManager = javaCompiler.getStandardFileManager(null, null, null);
			// 5.文件管理器根与文件连接起来
			Iterable it = javaFileManager.getJavaFileObjects(new File(dir, fullName + ".java"));
			// 6.创建编译任务
			CompilationTask task = javaCompiler.getTask(null, javaFileManager, null, Arrays.asList("-d", "./temp"),
					null, it);
			// 7.执行编译
			task.call();
			javaFileManager.close();

			// 8.运行程序
			Runtime run = Runtime.getRuntime();
			Process process = run.exec("java -cp ./temp " + packageName + fullName);
			InputStream in = process.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, encode));
			String info = "";
			while ((info = reader.readLine()) != null) {
				res += info + "\n";
			}
		} catch (Exception e) {
			res = e.getMessage();
		}
		return res;
	}
	// e

	//

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void test() throws IOException {
		// 1.创建需要动态编译的代码字符串
		String nr = "\r\n"; // 回车
		String source = "package temp.com; " + nr + " public class  Hello{" + nr
				+ " public static void main (String[] args){" + nr + " System.out.println(\"HelloWorld! 1\");" + nr
				+ " }" + nr + " }";
		// 2.将欲动态编译的代码写入文件中 1.创建临时目录 2.写入临时文件目录
		File dir = new File(System.getProperty("user.dir") + "/temp"); // 临时目录
		System.out.println("System.getProperty(\"user.dir\"):" + System.getProperty("user.dir"));
		// 如果 \temp 不存在 就创建
		if (!dir.exists()) {
			dir.mkdir();
		}
		FileWriter writer = new FileWriter(new File(dir, "Hello.java"));
		writer.write(source);
		writer.flush();
		writer.close();

		// 3.取得当前系统的编译器
		JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
		// 4.获取一个文件管理器
		StandardJavaFileManager javaFileManager = javaCompiler.getStandardFileManager(null, null, null);
		// 5.文件管理器根与文件连接起来
		Iterable it = javaFileManager.getJavaFileObjects(new File(dir, "Hello.java"));
		// 6.创建编译任务
		CompilationTask task = javaCompiler.getTask(null, javaFileManager, null, Arrays.asList("-d", "./temp"), null,
				it);
		// 7.执行编译
		task.call();
		javaFileManager.close();

		// 8.运行程序
		Runtime run = Runtime.getRuntime();
		Process process = run.exec("java -cp ./temp temp/com/Hello");
		InputStream in = process.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String info = "";
		while ((info = reader.readLine()) != null) {
			System.out.println(info);

		}
	}
	//
}